//
//  AppDelegate.m
//  Drops
//
//  Created by SHG on 16/5/20.
//  Copyright © 2016年 Drops.er. All rights reserved.
//

#import "AppDelegate.h"
#import "ZFK_squareMainViewController.h"
#import "ZFK_galleryMainViewController.h"
#import "LQL_photoMainViewController.h"
#import <BmobSDK/Bmob.h>
#import "LanuchViewController.h"
#import "StartView.h"

@interface AppDelegate ()

@property (nonatomic, assign)BOOL fromXC;       // 判断是否来自相册
@property (nonatomic, retain)UIImage *sourceImage;    // 相册选择/相机拍摄的图片

@end

/*
 * ARC模式编码
 * 基类(Model)已创建
 * 网址解析代码已添加
 * 基本三方已添加, 如有其他的需要自己加
 * Tools -> SaveTool为归档反归档方法封装
 * 命名规范: 新建文件时命名为 "姓名拼音缩写_文件名", 如"ZFK_mainCollectionView", 防止文件重名
 * 自定义的图标放到"ImageSource"文件夹中
 * 差不多这些了, 编码愉快.
 */

/*
 *图片编辑模式已修改
 *愉快
 */

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [Bmob registerWithAppKey:@"4a30626d4d4a05b227e4ab0c5f07a086"];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    ZFK_squareMainViewController *squareVC = [[ZFK_squareMainViewController alloc] init];
    UINavigationController *squareNaVC = [[UINavigationController alloc] initWithRootViewController:squareVC];
    squareNaVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"广场" image:[UIImage imageNamed:@"square.png"] tag:1000];
    
    ZFK_galleryMainViewController *galleryVC = [[ZFK_galleryMainViewController alloc] init];
    UINavigationController *gallerydNaVC = [[UINavigationController alloc] initWithRootViewController:galleryVC];
    gallerydNaVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"画廊" image:[UIImage imageNamed:@"gallery.png"] tag:1001];
    
    
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = @[squareNaVC, gallerydNaVC];
//    self.tabBarController.tabBar.tintColor = [UIColor colorWithRed:159 / 255.0 green:122 / 255.0 blue:121 / 255.0 alpha:1];
//    self.tabBarController.tabBar.tintColor = [UIColor colorWithRed:62 / 255.0 green:149 / 255.0 blue:196 / 255.0 alpha:1];
    self.tabBarController.tabBar.tintColor = [UIColor colorWithRed:88 / 255.0 green:91 / 255.0 blue:92 / 255.0 alpha:1];
    
    [self.window addSubview:self.tabBarController.view];
        [self addCenterTabbarButton];
    [self.window makeKeyAndVisible];
    self.tabBarController.tabBar.translucent = NO;
    self.tabBarController.view.backgroundColor = [UIColor whiteColor];
    
    NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
    if (![useDef boolForKey:@"notfirst"]) {
        LanuchViewController *vc =[[LanuchViewController alloc]init];
        self.window.rootViewController = vc;
        void(^block)(void) = ^(void){
            self.window.rootViewController = self.tabBarController;
        };
        vc.block = block;
    }else{
        self.window.rootViewController = self.tabBarController;
    }

    StartView *startView = [StartView startView];
    [startView startAnimationWithCompletionBlock:^(StartView *startView) {
    }];
    return YES;
}

- (void)addCenterTabbarButton {
    UIButton *centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *centerImage = [UIImage imageNamed:@"camera.png"];
    
    centerButton.frame = CGRectMake(0, 0, centerImage.size.width * 2, centerImage.size.height * 2);
    centerButton.layer.cornerRadius = centerImage.size.width;
//    centerButton.backgroundColor = [UIColor colorWithRed:243 / 255.0 green:67 / 255.0 blue:54 / 255.0 alpha:1];
    centerButton.backgroundColor = [UIColor colorWithRed:1 / 255.0 green:175 / 255.0 blue:240 / 255.0 alpha:1];
    [centerButton setImage:centerImage forState:0];
    [centerButton addTarget:self action:@selector(centerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    CGFloat imageHeight = centerImage.size.height;
    CGFloat barHeight = self.tabBarController.tabBar.frame.size.height;
    CGFloat delta = imageHeight - barHeight;
    
//    centerButton.hidden = YES;
    
    if (delta <= 0) {
        
        centerButton.center = CGPointMake(self.tabBarController.tabBar.center.x, self.tabBarController.tabBar.center.y + delta);
        
    } else {
        
        CGPoint center = self.tabBarController.tabBar.center;
        center.y = center.y - delta / 2.0;
        centerButton.center = center;
        
    }
    [self.tabBarController.view addSubview:centerButton];
    
}

- (void)centerButtonClick:(UIButton *)button {
    NSLog(@"centerButton did clicked");
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *XCAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:0 handler:^(UIAlertAction * _Nonnull action) {
            self.fromXC = YES;
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self.window.rootViewController presentViewController:imagePickerController animated:YES completion:^{
                
            }];
            
        }];
        UIAlertAction *XJAction = [UIAlertAction actionWithTitle:@"拍照" style:0 handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            self.fromXC = NO;
            [self.window.rootViewController presentViewController:imagePickerController animated:YES completion:^{
                NSLog(@"camera");
                
            }];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:XCAction];
        [alert addAction:XJAction];
        [alert addAction:cancelAction];
        
        [self.window.rootViewController presentViewController:alert animated:YES completion:^{
            
        }];
        
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *XCAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:0 handler:^(UIAlertAction * _Nonnull action) {
            self.fromXC = YES;
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self.window.rootViewController presentViewController:imagePickerController animated:YES completion:^{
                
            }];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:XCAction];
        [alert addAction:cancelAction];
        [self.window.rootViewController presentViewController:alert animated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    // 加判断
    self.sourceImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (self.fromXC == NO) {
        UIImageWriteToSavedPhotosAlbum(self.sourceImage, nil, nil, nil);
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    } else {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    LQL_photoMainViewController *picVC = [[LQL_photoMainViewController alloc] init];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = self.sourceImage;
    imageView.image = [self fixOrientation:imageView.image];
    picVC.picture = imageView.image;
    picVC.flag = self.fromXC;
    
    [picker pushViewController:picVC animated:YES];
    
}
//解决图片大小大于2M自动旋转90°的问题
- (UIImage *)fixOrientation:(UIImage *)aImage {
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "er.Drops" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Drops" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Drops.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
